<template>
    <div>
        <el-alert
                :closable="false"
                title="温馨提醒"
                type="success"
                description="编辑城市后，执行一下“保存到文件”，否则将会影响前端显示。">
        </el-alert>
        <!-- 搜索 -->
        <el-form :model="formItem"  label-width="80px" :inline="true" class="demo-form-inline" style="padding-top: 10px;">
            <el-form-item label="关键字">
                <el-input v-model="formItem.name" placeholder="关键字"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchSubmit('formItem')">搜索</el-button>
            </el-form-item>
        </el-form>
        <div style="margin-bottom: 10px;">
            <el-button @click.native="serviceAdd(0)" type="primary" size="small">添加</el-button>
            <el-button @click.native="deleteAll()" type="danger" size="small">删除</el-button>
            <el-button @click.native="saveFile()" type="primary" size="small" :loading="loading">保存到文件</el-button>
            <el-button v-if="parent_id >= 0" @click.native="back()" type="primary" size="small">返回上一级</el-button>
        </div>
        <el-table ref="selection" :data="listData" border tooltip-effect="dark" style="width: 100%"  @cell-dblclick="tableEdit" @selection-change="select">
            <el-table-column fixed type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="200"></el-table-column>
            <el-table-column prop="name" label="名称" width="200"></el-table-column>
            <el-table-column prop="short_name" label="简称" width="200"></el-table-column>
            <el-table-column prop="initials" label="首字母" width="200"></el-table-column>
            <el-table-column prop="sort" label="排序" width="200">
                <template slot-scope="scope">{{ scope.row.sort }}</template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="320">
                <template slot-scope="scope">
                    <el-button @click.native.prevent="serviceAdd(scope.row.id)" type="primary" size="mini">添加</el-button>
                    <el-button @click.native.prevent="getCityList(2,scope.$index)" type="primary" size="mini">查看下级</el-button>
                    <el-button @click.native.prevent="serviceEdit(scope.$index)" type="primary" size="mini">编辑</el-button>
                    <el-button @click.native.prevent="del(scope.$index)" type="danger" size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block" style="text-align : right; float : right; margin-top: 10px;">
            <!--<span class="demonstration">完整功能</span>-->
            <el-pagination
                    @size-change="handlePageSize"
                    @current-change="handlePage"
                    :current-page="pageNum"
                    :page-sizes="[10, 50, 100, 200]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal">
            </el-pagination>
        </div>

        <!-- 添加修改 -->
        <el-dialog :visible.sync="cityAdd" :title="titleStr" width="50%">
            <el-form ref="activity" :model="formAdd" :rules="formAddValidate" label-width="80px" class="demo-ruleForm">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formAdd.name" style="width:300px;"  placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item label="简称" prop="short_name">
                    <el-input v-model="formAdd.short_name" style="width:300px;"  placeholder="请输入简称"></el-input>
                </el-form-item>
                <el-form-item label="首字母" prop="initials">
                    <el-input v-model="formAdd.initials" style="width:300px;"  placeholder="请输入首字母"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number :min="1" :max="10000" v-model="formAdd.sort" style="width:300px;"  placeholder="请输入排序"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click.native="addSubmit('formAdd')">提交</el-button>
                    <el-button @click="addCancel()">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import axios from "@/axios";
    import { isIntNum, getHeaders } from "@/assets/js/common";
    export default {
        name: "city_list",
        data() {
            return {
                loading: false,
                base: {},
                headers: {},
                formItem: {
                    name: "",
                },
                formAdd: {
                    parent_id: [],
                    name: "",
                    short_name: "",
                    initials: "",
                    sort: 1
                },
                formAddValidate: {
                    position_id: [
                        {
                            type: 'number',
                            required: true,
                            message: "请选择父级",
                            trigger: "change"
                        }
                    ],
                    name: [
                        {
                            required: true,
                            message: "名称不能为空",
                            trigger: "blur"
                        }
                    ],
                    short_name: [
                        {
                            required: true,
                            message: "简称不能为空",
                            trigger: "blur"
                        }
                    ]
                },
                cityAdd:false,
                listData: [],
                ids: [],
                parent_id:-1,// 是否返回上一级
                titleStr:"",
                pageTotal: 0,
                pageNum: 1,
                pageSize: 10,
            };
        },

        mounted() {
            this.base = JSON.parse(sessionStorage.base);
            this.headers = getHeaders(localStorage._token);
            this.getCityList(1,'');
        },
        methods: {
            tableEdit(row, column, cell, event) {
                let vm = this;
                if (column.label) {
                    // 获取当前的值
                    var beforeVal = event.target.textContent;
                    event.target.innerHTML = "";
                    let str = `<div class='cell'>
                    <div class='el-input'>
                      <input type='text' placeholder='请输入内容' class='el-input__inner'>
                    </div>
                </div>`;
                    cell.innerHTML = str;
                    // 获取双击后生成的input  根据层级嵌套会有所变化
                    let cellInput = cell.children[0].children[0].children[0];
                    cellInput.value = beforeVal;
                    cellInput.focus(); // input自动聚焦
                    // 失去焦点后  将input移除
                    cellInput.onblur = function() {
                        let onblurCont = `<div class='cell'>${cellInput.value}</div>`;
                        cell.innerHTML = onblurCont; // 换成原有的显示内容
                        // 调用axios接口
                        if (column.property === 'sort'){
                            axios
                                .post("/admin/city/updateSort", {
                                    id: row.id,
                                    sort: cellInput.value
                                })
                                .then(response => {
                                    let status = response.status;
                                    let data = response.data;
                                    if (data.code === 200) {
                                        vm.$message({
                                            type: 'success',
                                            message: "操作成功!",
                                            onClose: function (msg) {
                                                vm.getCityList(1,"");
                                            }
                                        });
                                    } else {
                                        vm.$message.info(data.message);
                                    }
                                })
                                .catch(error => {
                                    // vm.$Message.info("网络或服务器异常");
                                });
                        }
                    };
                }
            },
            //获取勾选参数
            select(val) {
                let vm = this;
                vm.ids = [];
                for (let i in val) {
                    vm.ids.push(val[i].id);
                }
            },
            //搜索
            searchSubmit() {
                this.pageNum = 1;
                this.getCityList(2, '');
            },
            //当前页数
            handlePage(value) {
                this.pageNum = value;
                this.getCityList(1, '');
            },
            //每页显示条数
            handlePageSize(value) {
                this.pageSize = value;
                this.getCityList(1, '');
            },
            //获取城市列表
            getCityList(type,index){
                let vm = this;
                let father_id;
                if (type == 1) {
                    father_id  = vm.parent_id >= 0 ? vm.parent_id  : 0 ;
                }else{
                    father_id = index !== '' ? this.listData[index].id : vm.pid;
                }
                axios
                    .post("/admin/city/get-lists", {
                        pid: father_id,
                        page: this.pageNum,
                        limit: this.pageSize,
                        keyword: this.formItem.name
                    })
                    .then(response => {
                        let data = response.data;
                        if (data.code == 200) {
                            let result = data.data;
                            vm.pageTotal = result.total;
                            vm.listData = result.data;
                            vm.parent_id = result.parent_id;
                        } else {
                            vm.$message.info(data.message);
                        }
                    })
                    .catch(error => {
                        // vm.$message.info("网络或服务器异常");
                    });
            },
            //删除
            del: function (index = "") {
                let vm = this;
                //判断单条多条操作
                vm.ids = [];
                if (!isIntNum(index)) {
                    vm.ids.push(vm.listData[index].id);
                } else {
                    if (vm.ids.length < 1) {
                        vm.$message.error("请勾选数据！");
                        return false;
                    }
                }
                this.$confirm("是否确认删除吗？", "确认删除" , {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios
                        .post("/admin/city/delete", {
                            ids: vm.ids
                        })
                        .then(response => {
                            let status = response.status;
                            let data = response.data;
                            if (data.code == 200) {
                                vm.$message({
                                    type: 'success',
                                    message: "操作成功!",
                                    onClose: function (msg) {
                                        vm.getCityList(1,"");
                                        vm.ids = [];
                                    }
                                });
                            } else {
                                vm.$message.error(data.message);
                            }
                        })
                        .catch(error => {
                            //vm.$Message.info("网络或服务器异常");
                        });
                }).catch(() => {
                    vm.ids = [];
                    this.$refs.selection.selectAll(false);
                });
            },
            // 批量删除
            deleteAll() {
                let vm = this;
                if (vm.ids.length < 1) {
                    vm.$message.error("请勾选数据！");
                    return false;
                }
                this.$confirm("是否确认删除吗？", "确认删除" , {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios
                        .post("/admin/city/delete", {
                            ids: vm.ids
                        })
                        .then(response => {
                            let status = response.status;
                            let data = response.data;
                            if (data.code == 200) {
                                vm.$message({
                                    type: 'success',
                                    message: "操作成功!",
                                    onClose: function (msg) {
                                        vm.getCityList(1,"");
                                        vm.ids = [];
                                    }
                                });
                            } else {
                                vm.$message.error(data.message);
                            }
                        })
                        .catch(error => {
                            //vm.$Message.info("网络或服务器异常");
                        });
                }).catch(() => {
                    vm.ids = [];
                    this.$refs.selection.selectAll(false);
                });
            },
            // 添加框取消
            addCancel() {
                this.cityAdd = false;
                this.formAdd.id = 0;
                this.formAdd.name = "";
                this.formAdd.parent_id = 0;
                this.formAdd.short_name = "";
                this.formAdd.initials = "";
                this.formAdd.sort = 1;
            },
            // 添加、编辑处理
            addSubmit(name) {
                let vm = this;
                this.$refs.activity.validate(valid => {
                    if (valid) {
                        axios
                            .post("/admin/city/store", vm.formAdd)
                            .then(response => {
                                let status = response.status;
                                let data = response.data;
                                if (data.code == 200) {
                                    vm.cityAdd = false;
                                    vm.formAdd.id = 0;
                                    vm.formAdd.name = "";
                                    vm.formAdd.parent_id = 0;
                                    vm.formAdd.short_name = "";
                                    vm.formAdd.initials = "";
                                    vm.formAdd.sort = 1;
                                    vm.$message({
                                        type: 'success',
                                        message: "操作成功!",
                                        onClose: function (msg) {
                                            vm.getArticle();
                                        }
                                    });
                                } else {
                                    vm.$message.error(data.message);
                                }
                            })
                            .catch(error => {
                                // console.log(error);
                                // vm.$message.error("网络或服务器异常");
                            });
                    } else {
                        // vm.$message.error("Fail!");
                    }
                });
            },
            // 添加
            serviceAdd(pid) {
                let vm = this;
                vm.formAdd.pid = pid;
                vm.cityAdd = true;
                vm.titleStr = '添加';
            },
            // 保存到文件
            saveFile() {
                let vm = this;
                vm.loading = true;
                axios
                    .post("/admin/city/export", {
                        type:1 //  1全部 2市级+热门
                    })
                    .then(response => {
                        let data = response.data;
                        vm.loading = false;
                        if (data.code == 200) {
                            vm.$message({
                                type: 'success',
                                message: "操作成功!",
                                onClose: function (msg) {
                                    vm.getCityList(1,'');
                                }
                            });
                        } else {
                            vm.$message.info(data.message);
                        }
                    })
                    .catch(error => {
                        // vm.$Message.info("网络或服务器异常");
                    });
            },
            // 编辑
            serviceEdit(index) {
                let vm = this;
                vm.titleStr = '编辑';
                vm.formAdd.id = vm.listData[index].id;
                vm.formAdd.name = vm.listData[index].name;
                vm.formAdd.parent_id = vm.listData[index].parent_id;
                vm.formAdd.short_name = vm.listData[index].short_name;
                vm.formAdd.initials = vm.listData[index].initials;
                vm.formAdd.sort = vm.listData[index].sort;
                vm.cityAdd = true;
            },
            // 返回上一级
            back() {
                this.getCityList(1,this.parent_id);
            }
        }
    }
</script>

<style scoped>

</style>